Page({
  data: {
    weatherData: {
      city: '',
      dateList: [],
      selectedDate: null
    },
  },
  onLoad: function(options) {
    if (options.cityName) {
      this.getWeatherData(options.cityName); // 传递cityName到API
    }
  },
  // weather.js 中 getWeatherData 优化日期处理
getWeatherData(city) {
  const url = `https://gfeljm.tianqiapi.com/api?unescape=1&version=v9&appid=14261918&appsecret=7iy4ZSep&city=${city}`;
  wx.request({
    url: url,
    method: 'GET',
    success: (res) => {
      if (res.data && res.data.data && res.data.data.length > 0) {
        const dateList = res.data.data.map(item => ({
          ...item,
          selected: false // 初始化选中状态
        }));
        const today = new Date().toLocaleDateString('zh-CN'); // 转换为本地日期格式
        // 兼容不同日期格式的匹配
        const selectedDay = dateList.find(day => {
          const dayDate = day.date.split('-').join('/'); // 假设API返回YYYY-MM-DD，转换为YYYY/MM/DD
          return dayDate === today;
        }) || dateList[0];
        if (selectedDay) {
          selectedDay.selected = true;
        }
        const weatherData = {
          city: res.data.city,
          dateList,
          selectedDate: selectedDay
        };
        this.setData({
          weatherData
        });
      } else {
        wx.showToast({
          title: '获取天气失败',
          icon: 'error'
        });
      }
    },
    fail: () => {
      wx.showToast({
        title: '网络请求失败',
        icon: 'none'
      });
    }
  });
},
  // weather.js 中 selectDate 优化数据更新
selectDate(event) {
  const selectedDate = event.currentTarget.dataset.date;
  let { dateList } = this.data.weatherData;
  // 创建新数组并更新选中状态
  dateList = [...dateList].map(day => ({
    ...day,
    selected: day.date === selectedDate
  }));
  const selectedDay = dateList.find(day => day.date === selectedDate);
  this.setData({
    'weatherData.dateList': dateList,
    'weatherData.selectedDate': selectedDay || dateList[0]
  });
}
});
